#include "net.h"
#include <iostream>

using std::cerr;
// 
// Socket methods
//
net::Socket::Socket(int socket, bool activate) {
    this->socket = socket;
    if (activate) {
        connect();
    }
}

net::Socket::Socket(int socket, sockaddr_in* remote_addr, socklen_t len) {
    this->socket = socket;
    char* ip = inet_ntoa(remote_addr->sin_addr);
    cerr << "accepted from " << ip << "\n";

}

int net::Socket::id() {
    return socket;
}

void net::Socket::connect() {
}

net::Socket::~Socket() {
}

// 
// ServerSocket methods
//
net::ServerSocket::ServerSocket(int port, bool activate) {
    socket_id = socket(PF_INET, SOCK_STREAM, 0);
    address.sin_family = AF_INET;
    address.sin_port = htons(port);
    address.sin_addr.s_addr = INADDR_ANY;
    if (activate) {
        bind();
        listen();
    }
}

void net::ServerSocket::bind() {
    int res = ::bind(socket_id, (sockaddr*)&address,
        sizeof(struct sockaddr_in));
    if (res != 0) {
        //throw IOException();
    }
}

void net::ServerSocket::listen() {
    int res = ::listen(socket_id, LISTEN_QUEUE_SIZE);
    
    if (res != 0) {
        //throw IOException();
    }
}

net::Socket* net::ServerSocket::accept() {
    sockaddr_in* remote_addr = new sockaddr_in();
    socklen_t remote_addr_len;
    int socket = ::accept(socket_id, (sockaddr*)remote_addr,
        &remote_addr_len);

    if (socket < 0) {
        //throw new IOException("accept failed", socket);
    }

    return new Socket(socket, remote_addr, remote_addr_len);
}

net::ServerSocket::~ServerSocket() {
}

